import 'dart:convert';

import 'package:chi_med_det_flutter/answer_list.dart';
import 'package:chi_med_det_flutter/url.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<StatefulWidget> createState() => _HomeState();
}

class Question {
  int no;
  String title;
  List<dynamic> options;
  int selectIndex;

  Question(this.no, this.title, this.options, this.selectIndex);
}

class _HomeState extends State<Home> {
  final List<Question> _questionList = [];
  final List<int> _selectIndexList = [];

  void showSnakeBar(String content) {
    final snackBar = SnackBar(
      content: Text(content),
      duration: Duration(seconds: 3),
      action: SnackBarAction(label: "知道了", onPressed: () {}),
    );
    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  void submit() {
    AnswerList answerList = Provider.of<AnswerList>(context, listen: false);
    answerList.clearAnswer();
    for (int i = 0; i < _selectIndexList.length; i++) {
      if (_selectIndexList[i] == -1) {
        showSnakeBar('请先完成问卷调查');
        return;
      } else {
        answerList.addAnswer(Answer(i, _selectIndexList[i]));
      }
    }
  }

  @override
  void initState() {
    super.initState();
    requestQuestionList();
  }

  void requestQuestionList() async {
    final url = Uri.parse(URL.GET_QUESTION_LIST);
    final response = await http.get(url);
    Map<String, dynamic> res = jsonDecode(response.body);
    if (response.statusCode == 200) {
      var questionList = res['questionList'];
      if (questionList != null && questionList is List) {
        for (int index = 0; index < questionList.length; index++) {
          final q = Question(
            questionList[index]['no'],
            questionList[index]['title'],
            questionList[index]['options'],
            questionList[index]['selectIndex'],
          );
          if (mounted) {
            setState(() {
              _questionList.add(q);
              _selectIndexList.add(-1);
            });
          }
        }
      }
    }
  }

  List<Widget> makeRadioList(int i, List<dynamic> options, int selectIndex) {
    List<Widget> radioList = [];
    for (int index = 0; index < options.length; index++) {
      // TODO Why?
      radioList.add(
        RadioListTile(
          contentPadding: EdgeInsets.zero,
          groupValue: _selectIndexList[i],
          value: index,
          onChanged: (int? value) {
            setState(() {
              _selectIndexList[i] = value!;
            });
          },
          title: Text(options[index].toString()),
        ),
      );
      // radioList.add(
      //   Radio(
      //     groupValue: _selectIndexList[i],
      //     value: index,
      //     onChanged: (int? value) {
      //       setState(() {
      //         _selectIndexList[i] = value!;
      //       });
      //     },
      //   ),
      // );
      // radioList.add(Text(options[index].toString()));
    }
    return radioList;
  }

  List<Widget>? makeItemList() {
    List<Widget> itemList = [];
    for (int i = 0; i < _questionList.length; i++) {
      itemList.add(
        Padding(
          padding: EdgeInsets.fromLTRB(10, 0, 20, 0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                "${_questionList[i].no}.${_questionList[i].title}",
                style: TextStyle(fontSize: 20),
              ),
              Column(
                children: (makeRadioList(
                  i,
                  _questionList[i].options,
                  _questionList[i].selectIndex,
                )),
              ),
            ],
          ),
        ),
      );
    }
    if (itemList.isNotEmpty) {
      return itemList;
    } else {
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(height: 20),
          Expanded(child: ListView(children: makeItemList() ?? [Text("暂无数据")])),
          TextButton(
            onPressed: () {
              submit();
            },
            style: ButtonStyle(
              foregroundColor: WidgetStateProperty.all(Colors.white),
              backgroundColor: WidgetStateProperty.resolveWith<Color>((states) {
                if (states.contains(WidgetState.pressed)) {
                  return Colors.accents.first;
                }
                return Colors.purple;
              }),
            ),
            child: Padding(
              padding: EdgeInsets.fromLTRB(20, 5, 20, 5),
              child: const Text(
                "提交",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
              ),
            ),
          ),
          SizedBox(height: 50),
        ],
      ),
    );
  }
}
